package com.hcss.common.util;

import com.hcss.common.constant.CommonConstants;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.Set;

/**
 * @描述: 字段校验工具类
 * @作者: xuqian
 * @创建日期: 2018-10-18 11:45
 * @公司 浙江鸿程计算机系统有限公司
 */
public class ValidatorUtil {
    private static final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();


    /**
     * 校验全部字段,返回拼接的错误信息
     * @param obj
     * @return
     */
    public static<T> String validateAll(T obj) {
        StringBuilder stringBuilder = new StringBuilder();
        Set<ConstraintViolation<T>> set = validator.validate(obj, Default.class);
        if (CollectionUtils.isNotEmpty(set)) {
            for (ConstraintViolation<T> cv : set) {
                stringBuilder.append(cv.getPropertyPath()).append(CommonConstants.SPACE)
                        .append(cv.getMessage()).append(CommonConstants.COMMA);
            }
        }

        String message = stringBuilder.toString();
        return StringUtils.isBlank(message) ? message : message.substring(0, message.length() - 1);
    }
}
